/**
 * Copyright (c) 2011 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.android.tools;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.media.MediaPlayer;
import android.util.Log;

public class SoundBank {
  private final Activity myActivity;
  private Map<Integer, MediaPlayer> mySounds = new HashMap<Integer, MediaPlayer>();
  private ExecutorService mySoundPlayerService = Executors.newSingleThreadExecutor();
  
  public SoundBank( Activity aActivity ) {
    super();
    myActivity = aActivity;
  }

  public void play(final int aSoundId){
    mySoundPlayerService.execute( new Runnable(){
      public void run(){
        try{
        if(!mySounds.containsKey( aSoundId )){
          loadSound(aSoundId);
        }
        
        mySounds.get(aSoundId).start();
        }catch(Exception e){
          Log.e( SoundBank.class.getName(), "Could not play sound", e);
        }
      }
    });
  }
  
  private void loadSound(int aSoundId) throws IllegalStateException, IOException{
    MediaPlayer thePlayer = MediaPlayer.create( myActivity, aSoundId );
//    thePlayer.prepare();
    mySounds.put( aSoundId, thePlayer );
  }
}
